package com.jzoom.zoom.aop.reflect;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * java反射相关工具类
 * 
 * 
 * @author jzoom
 *
 */
public class ReflectKit {
	
	/**
	 * 获取函数的泛型参数类型
	 * @param method		 函数
	 * @param paramIndex 参数下标
	 * @param genericIndex 泛型下标
	 * 
	 * 对于
	 * 
	 * void method1(List<String> list, Map<String,Long> map);
	 * 
	 * 可以这么获取:
	 * 
	 * getGenericParameterType( method,  0,0  )  =>  java.lang.String
	 * getGenericParameterType( method,  1,1  )  =>  java.lang.Long
	 * 
	 * 假设对应的下标不是泛型，或者超标了，那么就报RuntimeException
	 * 
	 * 
	 * @return
	 */
	public static Class<?> getGenericParameterType(Method method,int paramIndex,int genericIndex){
		
		if(method==null) {
			throw new NullPointerException();
		}
		if(paramIndex <0 || genericIndex < 0) {
			throw new RuntimeException("Zero");
		}
		
		
		
		Type[] types = method.getGenericParameterTypes();
		if(paramIndex >= types.length) {
			throw new RuntimeException("{paramIndex} is too big");
		}
		Type type = types[paramIndex];
		if(type instanceof ParameterizedType) {
			Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
			if(genericIndex >= actualTypeArguments.length) {
				throw new RuntimeException("{genericIndex} is too big");
			}
			if( actualTypeArguments[genericIndex] instanceof Class) {
				return (Class<?>)actualTypeArguments[genericIndex];
			}
			Class<?>[] paramTypes = method.getParameterTypes();
			return paramTypes[paramIndex];
		}
		
		if(genericIndex > 0) {
			throw new RuntimeException("{genericIndex} is too big");
		}
		
		return (Class<?>) type;
	}
	
	/**
	 * 一下子取得全部泛型
	 * @param method
	 * @return
	 */
	public static Class<?>[][] getGenericParameterTypes(Method method){
		
		
		
		return null;
	}
}
